# -*- coding:utf-8 -*-

# from odoo import api, fields, models, _
# from odoo.exceptions import UserError, ValidationError
# from . import membership

from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
import random
import string

class Partner(models.Model):
    # _inherit = 'res.partner'
    _inherit = 'res.partner'

    member_no = fields.Char(help="Member No.",string = "Member No.", copy=False)


    _sql_constraints = [
        ('member_no_uniq', 'unique(member_no)',
         'The Member Number must be unique across the company(s).'),
    ]

    @api.model
    def _generate_identification_id(self):
        """Generate a random employee identification number"""
        # company = self.env.user.company_id
        member_no = False

        member_no_random_digits = 8 # 8 digits for member No.
        tries = 0
        max_tries = 50
        while tries < max_tries:
            rnd = random.SystemRandom()
            member_no = ''.join(rnd.choice(string.digits)
                                  for _ in
                                  xrange(member_no_random_digits))
            if not self.search_count([('member_no',
                                       '=',
                                       member_no)]):
                break
            tries += 1
        if tries == max_tries:
            raise UserWarning(_('Unable to generate an Member No. that \
            is unique.'))
        return member_no

    @api.model
    def create(self, vals):
        eid = self._generate_identification_id()
        vals['member_no'] = eid
        return super(Partner, self).create(vals)
